<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: `${editing ? '编辑' : '新增'}预约`,
			size: '700px',
			appendToBody: true
		}"
		showConfirm
		confirmText="提交预约"
		@close="reset"
		@confirm="submit"
		:saving="saving"
	>
		<el-form ref="form" label-position="top" :model="form" :rules="rules" :disabled="saving">
			<el-form-item label="预约信息">
				<el-card shadow="never">
					<el-row :gutter="20">
						<el-col :span="12">
							<el-form-item label="预约事业部" prop="biz_id">
								<cl-select
									v-model="form.biz_id"
									placeholder="请选择预约事业部"
									filterable
									style="width: 100%"
									:disabled="editing"
									@change="changeBizId"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="品牌" prop="bra_id">
								<cl-select
									v-model="form.bra_id"
									placeholder="请选择品牌"
									filterable
									style="width: 100%"
								>
									<el-option
										v-for="item in bizRefData.brand"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<!-- <el-col :span="12">
							<el-form-item label="预约部门" prop="add_dept_id">
								<cl-cascader
									style="width: 100%"
									v-model="form.add_dept_id"
									@change="changeAppointDept"
									:options="deptList"
								/>
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item label="预约人" prop="add_user_id">
								<cl-select
									style="width: 100%"
									v-model="form.add_user_id"
									placeholder="请选择"
									filterable
								>
									<el-option
										v-for="(item, index) in appointUser"
										:key="index"
										:label="item.user_name"
										:value="item.user_id"
									/>
								</cl-select>
							</el-form-item>
						</el-col> -->
						<template v-if="!editing">
							<el-col :span="24">
								<el-form-item label="是否指定预约时间" prop="timeIsok" required>
									<el-radio-group
										v-model="form.timeIsok"
										@change="timeIsokChange"
									>
										<el-radio :label="0">否</el-radio>
										<el-radio :label="1">是</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
							<template v-if="form.timeIsok == 1">
								<el-col :span="form.appoint_time ? 12 : 9">
									<el-form-item label="预约时长" prop="cart_duration">
										<cart-duration
											v-model="form.cart_duration"
											style="width: 100%"
											:disabled="this.cart_duration_disabled"
										/>
									</el-form-item>
								</el-col>
								<el-col :span="form.appoint_time ? 12 : 10">
									<el-form-item label="预约城市" prop="city_id">
										<cl-select
											v-model="form.city_id"
											placeholder="请选择"
											filterable
											clearable
											:disabled="!!form.appoint_time"
											style="width: 100%"
										>
											<el-option
												v-for="item in cityList"
												:key="item.value"
												:label="item.label"
												:value="item.value"
											/>
										</cl-select>
									</el-form-item>
								</el-col>
								<template v-if="form.appoint_time">
									<el-col :span="12">
										<el-form-item label="预约门店" prop="dept_id">
											<cl-shop-select
												v-model="form.dept_id"
												placeholder="请选择预约门店"
												filterable
												style="width: 100%"
												disabled
												only-open
												:biz_id="form.biz_id"
											/>
										</el-form-item>
									</el-col>
									<el-col :span="12">
										<el-form-item prop="appoint_time" label="预约时间">
											<el-input
												v-model="form.appoint_time"
												type="text"
												placeholder="请填写预约时间"
												disabled
											/>
										</el-form-item>
									</el-col>
								</template>
								<el-col :span="form.appoint_time ? 24 : 5">
									<el-form-item :label="form.appoint_time ? '' : ' '">
										<div style="text-align: center">
											<el-button
												type="primary"
												size="mini"
												@click="onSelectTime"
												>预约门店/时间</el-button
											>
										</div>
									</el-form-item>
								</el-col>
							</template>
						</template>
					</el-row>
				</el-card>
			</el-form-item>
			<el-form-item label="预约服务" prop="serviceList">
				<cl-service-card :biz_id="form.biz_id" v-model="form.serviceList" />
			</el-form-item>
			<el-form-item label="预约备注" prop="remarks">
				<el-input
					v-model="form.remarks"
					placeholder="请填写预约备注"
					type="textarea"
					:rows="3"
				/>
			</el-form-item>
		</el-form>
	</cl-drawer>
</template>
<script>
	import dayjs from "dayjs";
	import CartDuration from "@/components/cart-duration.vue";
	// import { cityList } from "@/assets/countryLevel3";

	export default {
		name: "cl-appoint-form",
		components: {
			CartDuration
		},
		inject: ["$layout"],
		props: {
			// 是否是编辑状态
			isEdit: {
				type: Boolean,
				default: false
			},
			disabledBiz: {
				type: Boolean,
				default: false
			}
		},
		data() {
			const appointTimeValidator = (rule, value, callback) => {
				const { appoint_date, appoint_btime } = this.form;
				if (!appoint_date || !appoint_btime) {
					return callback(new Error("请选择预约时间"));
				}
				return callback();
			};
			return {
				cityList:[],
				form: {
					cart_id: undefined,
					bed: undefined,
					biz_id: "", //事业部id
					dept_id: "", //门店id
					bra_id: "",
					add_dept_id: [], //预约部门
					add_user_id: "", //预约人
					// dept_ids: [],
					cus_id: "", //客户名
					cus_mobile: "", //客户手机
					timeIsok: 0, //是否需要预约时间
					appoint_time: null,
					appoint_date: "", //预约日期
					appoint_btime: "", //预约开始时间
					cart_duration: "", // 预约时长
					appoint_time_diff: undefined,
					// appoint_etime: "", //预约结束时间
					serviceList: [], //已选服务列表
					remarks: "", //备注信息
					city_id: ""
					// region: "",
					// date1: "",
					// date2: "",
					// delivery: false,
					// type: [],
					// resource: "",
					// desc: ""
				},
				rules: {
					biz_id: [{ required: true, message: "请选择预约事业部" }],
					bra_id: [{ required: true, message: "请选择品牌" }],
					dept_id: [{ required: true, message: "请选择预约门店" }],
					// add_dept_id: [{ required: true, message: "请选择预约部门" }],
					// add_user_id: [{ required: true, message: "请选择预约人" }],

					cus_id: [{ required: true, message: "请选择会员姓名" }],
					appoint_time: [{ required: true, validator: appointTimeValidator }],
					cart_duration: [{ required: true, message: "请选择预约时长" }],
					city_id: [{ required: true, message: "请选择城市" }],
					// appoint_btime: [
					//   { required: true, message: "请选择预约时间" },
					// ],
					serviceList: [
						{
							// type: "array",
							required: true,
							message: "请选择预约服务"
						}
					]
				},
				deptList: [], //部门列表
				appointUser: [], //预约人列表
				memberList: [], //会员列表
				editing: this.isEdit,
				saving: false,
				cart_duration_disabled: false
			};
		},
		computed: {
			bizRefData() {
				const { biz_id } = this.form;
				return this.getBizRefData(biz_id);
			}
		},
		watch: {
			isEdit(v) {
				this.editing = v;
			}
		},
		created() {
			this.form.biz_id = this.getCurrBiz();
			
		},
		methods: {
			async open(data = {}, editing) {
				editing != undefined && (this.editing = editing);
				this.$store.commit("common/SET_VISIBLE_APPOINT_FORM", true);
				this.$refs.drawer.create();

				Object.keys(this.form).forEach((key) => {
					data[key] != undefined && (this.form[key] = data[key]);
				});
				if (this.form.dept_id == 0) {
					this.form.dept_id = "";
				}
				if (this.form.cart_duration == 0) {
					this.form.cart_duration = "";
					this.cart_duration_disabled = false;
				}
				this.form.appoint_time = null;
				if (this.editing) {
					console.log("data", data);
					const { appoint_date, appoint_etime, appoint_time } = data;
					let timeIsok = appoint_date && appoint_date != "待定时间" ? 1 : 0;
					this.form.timeIsok = timeIsok;
					this.form.appoint_date = "";
					if (timeIsok) {
						let date = dayjs(appoint_date);
						this.form.appoint_date = date.format("YYYY-MM-DD");
						this.form.appoint_btime = date.format("HH:mm");

						if (appoint_etime) {
							let etime = dayjs(date.format("YYYY-MM-DD") + " " + appoint_etime);
							this.form.appoint_time_diff = etime.diff(date, "m");
						}
						this.form.appoint_time = [this.form.appoint_date, this.form.appoint_btime].join(
							" "
						);
					}
					if (data.add_depts) {
						let add_depts = data.add_depts.split(",").map((v) => Number(v));
						this.form.add_dept_id = [data.biz_id, add_depts[1], add_depts[0]];
					}

					this.form.serviceList = (data.service_info || []).map((v) => {
						return {
							...v,
							si_id: v.id,
							si_name: v.name,
							price: v.unit_price,
							maintain_type: v.maintain_type || 0
						};
					});
					// if (!this.shopList.length) return;
					// this.form.dept_ids = [this.shopList[0].dept_id, data.dept_id * 1];
				} else {
					if (data.cus_type == 2) {
						this.getDefaultser(data);
					}
				}
				const { biz_id, add_dept_id, add_user_id } = this.form;
				this.initBizRefData();
				this.getDeptList(biz_id);
				this.changeAppointDept(add_dept_id);
				this.getCityList()
				// this.getUserList({
				// 	biz_id: this.form.biz_id,
				// 	dept_id: this.form.add_dept_id[0]
				// });
			},
			initBizRefData() {
				const { biz_id } = this.form;
				this.getBizRefBrand(biz_id);
				this.getBizRefShop(biz_id);
				this.getDeptList(biz_id);
			},
			//获取默认服务
			async getDefaultser(row) {
				let { biz_id, cus_id } = row;
				let data = await this.$service.cart.getDefaultser({
					biz_id,
					cus_id
				});
				if (data && data.length) {
					this.form.serviceList.push({
						is_presents: 0,
						is_experience: 0,
						si_id: data[0].si_id,
						si_name: data[0].si_name,
						price: data[0].price
					});
				}
			},
			reset() {
				this.$resetFields(this.form);
				this.form.cart_duration = "";
				this.$refs.form.resetFields();
				this.$store.commit("common/SET_VISIBLE_APPOINT_FORM", false);
			},
			close() {
				this.$refs.drawer.close();
			},
			submit() {
				this.$refs.form.validate(async (valid, errors) => {
					this.showFormErr(errors);
					if (!valid) return;

					const { serviceList, dept_ids, add_dept_id, appoint_time_diff, ...args } =
						this.form;
					let items = serviceList.map((v) => {
						return {
							type: 1,
							id: v.si_id,
							prod_id: v.si_id,
							name: v.si_name,
							lasttime: v.lasttime,
							picture_url: v.picture_url,
							product_category: v.product_category,
							unit_price: v.price,
							price: v.price,
							maintain_type: v.maintain_type || 0,
							is_presents: v.is_presents,
							is_experience: v.is_experience
						};
					});
					let form = {
						...args,
						add_dept_id: add_dept_id[2] || 0,
						items: JSON.stringify(items),
						update_type: 1
					};
					// if (appoint_time_diff) {
					// 	form.appoint_etime = dayjs(form.appoint_time)
					// 		.add(appoint_time_diff, "m")
					// 		.format("HH:mm");
					// }
					this.$delete(form, "timeIsok");
					this.saving = true;
					await this.$service.cart[this.editing ? "updateCart" : "add"](form).done(() => {
						this.saving = false;
					});
					this.$message.success("操作成功");
					this.$emit("confirm");
					this.close();
				});
			},
			// 更改预约事业部
			async changeBizId() {
				// this.form.dept_id = "";
				this.form.bra_id = "";
				// if (!this.editing) {
				// 	this.form.bra_id = this.bizRefData.brand[0]?.bra_id ?? "";
				// }
				this.initBizRefData();
				this.getCityList()
			},
			// 切换门店
			changeDept(val) {
				// this.form.dept_id = v[1];
				// this.form.cus_id = "";
				if (!val) return;
				this.form.appoint_btime = "";
				this.memberList = [];
			},
			//获取预约部门
			async getDeptList(biz_id) {
				// let biz_id = this.getCurrBiz(true);
				const data = await this.$service.dept.preDept({
					parent_id: 0,
					biz_id
					// is_store: 1
				});
				let deptList = data || [];
				let list = this.bizList.map((biz) => {
					return {
						id: biz.biz_id,
						value: biz.biz_id,
						label: biz.biz_name,
						children: deptList
							.filter((item) => biz.biz_id == item.biz_id)
							.map((item) => {
								let newItem = {
									id: item.dept_id,
									value: item.dept_id,
									label: item.dept_name,
									children: []
								};
								if (item.children && item.children.length) {
									newItem.children = item.children
										.filter((subItem) => subItem.parent_id == item.dept_id)
										.map((subItem) => {
											return {
												id: subItem.dept_id,
												value: subItem.dept_id,
												label: subItem.dept_name
											};
										});
								}
								return newItem;
							})
					};
				});
				this.deptList = list;
			},
			async changeAppointDept(v, is_reset = true) {
				is_reset && (this.form.add_user_id = "");
				this.appointUser = [];
				this.appointUser = await this.getUserList({
					biz_id: v[0],
					dept_id: v[2]
				});
			},
			async getUserList(params) {
				const { data } = await this.$service.user.list(params).catch(() => []);
				return data || [];
			},
			timeIsokChange(v) {
				if (v) return;
				this.form.appoint_date = "";
				this.form.appoint_btime = "";
				this.form.cart_duration = "";
			},
			// 选择预约时间
			onSelectTime() {
				const { biz_id, dept_id, cart_duration, city_id } = this.form;

				if (!cart_duration) {
					this.$message.warning("请先选择预约时长！");
					return false;
				}
				if (!city_id) {
					this.$message.warning("请先选择预约城市！");
					return false;
				}

				const params = {
					biz_id: biz_id,
					dept_id: dept_id,
					cart_duration: cart_duration,
					city_id: city_id
				};
				this.$layout.openAppointBoard(
					params,
					"选择预约时间",
					"selectTime",
					this.selectTimeCall
				);
			},
			selectTimeCall(data = null) {
				console.info("我是个回调回来的数据", data);
				if (!data) return false;

				this.form.dept_id = data.dept_id;
				// this.form.appoint_time = data.appoint_time;
				this.$set(this.form, "appoint_time", data.appoint_time);
				this.form.appoint_date = data.appoint_date;
				this.form.appoint_btime = data.appoint_btime;
				this.form.city_id = data.city_id;

				if (data.cart_duration > 0) {
					this.cart_duration_disabled = true;
					this.form.cart_duration = data.cart_duration;
				}
				else {
					this.cart_duration_disabled = false;
				}
			},
			//获取城市列表
			async getCityList(){
				 const {biz_id} = this.form
				 this.$service.spread.newGetbizcity({ biz_id }).then(data => {
					let list = (data || []).map(v => ({ ...v, label: v.name, value: v.id }));
					this.cityList = list
				})
			}
		}
	};
</script>
<style lang="scss" scoped>
	::v-deep {
		.el-col {
			min-height: 78px;
		}
	}
</style>
